﻿///
///列表数据处理器，自动处理分页，加载更多的逻辑
///
(function($) {
	$.fn.listviewHandler = function() {
		var $this = this;
		if($this.data('listviewHandler')) {
			return $this.data('listviewHandler');
		}

		$this.data('listviewHandler', this);
		//初始化
		$this.initialize = function(options) {
			var defoption = {
				loaderBtn: '', //加载数据按钮（点击加载下一页）
				emptyHtml: '无记录', //无记录时显示此html
				itemTemplate: '', //项模板
				pageIndex: 1, //页码（从1起算）
				pageSize: 20, //页大小
				totalCount: 999, //总记录数
				itemHandler: function(data, itemTemplate, container) { //数据各项处理
					return itemTemplate.format(data);
				},
				beforeHandleResult: function(result, totalCount, container) {},
				afterHandleResult: function(result, totalCount, container) {},
				command: '',
				parameter: {}
			};
			$this.options = $.extend({}, defoption, options);

			//          $this.options.loaderBtn.click(function () {
			//              $this.nextPage();
			//          });

			//隐藏加载按钮
			$this.options.loaderBtn.hide();

			//清空现有数据
			$this.empty();
		}

		//加载下一页
		$this.nextPage = function() {
			var param = $.extend({}, {
				PageIndex: $this.options.pageIndex,
				PageSize: $this.options.pageSize
			}, $this.options.parameter);
			//调用接口
			$this.executeCommand({
				successCallBack: function(result, totalCount) {
					$this.options.beforeHandleResult(result, totalCount, $this);
					if(totalCount == 0) {
						$this.append($this.options.emptyHtml);
					}

					if($this.options.pageSize * $this.options.pageIndex < totalCount) {
						$this.options.loaderBtn.show();
					} else {
						$this.options.loaderBtn.hide();
						$this.options.loaderBtn.unbind()
					}

					$this.options.totalCount = totalCount;
					$this.options.pageIndex += 1;
					//遍历所有属性，找出array的属性作为列表数据
					for(var prop in result) {
						if(result[prop] instanceof Array) {
							$(result[prop]).each(function() {
								var html = $this.options.itemHandler(this, $this.options.itemTemplate, $this);

								$this.append(html);
							});
						}
					}
					$this.options.afterHandleResult(result, totalCount, $this);
				}
			}, $this.options.command, param);
		}

		return $this;
	}
})(jQuery);